#include "ads1118.h"
#include "spi.h"
#include <string.h>

ADS_InitTypeDef adsConfigReg;
// SPI收发函数
uint16_t SPI_ReadWrite16Bit(uint16_t data) {
    uint16_t rxData = 0;
    HAL_StatusTypeDef status;
    // 发送和接收数据
    status = HAL_SPI_TransmitReceive(&hspi1, (uint8_t*)&data, (uint8_t*)&rxData, 1, HAL_MAX_DELAY);
    if (status != HAL_OK) {
        Error_Handler();  // 进入错误处理
    }
    return rxData;
}
//温度电压值 K型热电偶
//第一列为温度 第二列为电压单位是mv
type_k_thermo_lookup_entry_table type_k_thermo_lookup[TYPE_K_THERMO_LOOKUP_SIZE] = {
	{-250, -6.18},// {-200,-5.891},
	{-200, -5.603},// {-100,-3.554},
	{-150, -4.648},// {0,0},
	{-100, -3.379},// {100,4.096},
	{-50 , -1.819},// {200,8.138},
	{0   , 0     },// {300,12.209},
	{ 25, 0.992},
	{ 50, 2.036},// {400,16.397},
	{ 75, 3.132},
	{100 , 4.279},// {500,20.644},
	{150 , 6.704},// {600,24.905},
	{200 , 9.288},// {700,29.129},
	{250 , 12.013},// {800,33.275},
	{300 , 14.862},// {900,37.326},
	{350 , 17.819},// {1000,41.276},
	{400 , 20.872}// {1100,45.119},
	// {1200,48.838},
	// {1300,52.410}
};
// 获取冷端温度
float ads1118_get_temperature(void) {
	uint16_t adc=0;
	float value=0;
	adsConfigReg.stru.NOP     =  DATA_VALID;
	adsConfigReg.stru.TS_MODE =  TEMPERATURE_MODE;
	adsConfigReg.stru.DR      =  DR_860_SPS;
	adsConfigReg.stru.MODE    =  SIGNLE_SHOT;
	adsConfigReg.stru.OS      =  SINGLE_CONVER_START; 
	adsConfigReg.stru.PULLUP  =  PULL_UP_EN;	
	adsConfigReg.stru.RESV	  =  CONFIG_BIT_RESV;
	ADS1118_ENABLE;
	adc = SPI_ReadWrite16Bit(adsConfigReg.word);
	ADS1118_DISABLE;
	HAL_Delay(1);
	ADS1118_ENABLE;
	adsConfigReg.stru.NOP     =  DATA_INVALID;
	adsConfigReg.stru.TS_MODE =  TEMPERATURE_MODE;
	adsConfigReg.stru.DR      =  DR_860_SPS;
	adsConfigReg.stru.MODE    =  SIGNLE_SHOT;
	adsConfigReg.stru.OS      =  SINGLE_CONVER_START; 
	adsConfigReg.stru.PULLUP  =  PULL_UP_EN;	
	adsConfigReg.stru.RESV	  =	 CONFIG_BIT_RESV;
    HAL_Delay(3);
	adc = SPI_ReadWrite16Bit(adsConfigReg.word);
	ADS1118_DISABLE;
	//conver to temperture
	if(adc&0x8000) {
		adc>>=2;
		value=(0x3fff-adc+1)*(-0.03125);
	} else {
		adc>>=2;
		value=adc*0.03125;     
	}
	return value;
}

int8_t  ads1118_get_temp_thermo_type_k( double input_voltage_mV, double input_cold_junction_C, double *output_hot_junction_C) {
    const type_k_thermo_lookup_entry_table  *type_k_thermo_lookup_table;
    uint8_t type_k_thermo_lookup_size;
	uint32_t i=1;
    double total_mV;
	type_k_thermo_lookup_table = type_k_thermo_lookup;
	type_k_thermo_lookup_size  = TYPE_K_THERMO_LOOKUP_SIZE;
    // 查看数据是否超出范围
    if ( (input_cold_junction_C < type_k_thermo_lookup_table[0].temp_C) ||
         (input_cold_junction_C > type_k_thermo_lookup_table[type_k_thermo_lookup_size-1].temp_C) ) {
        *output_hot_junction_C = 0;
        return -1;
    }
	// 查找冷端温度所在的位置
    while ( i<(type_k_thermo_lookup_size-1)) {
        if ( input_cold_junction_C <= type_k_thermo_lookup_table[i].temp_C ) {
            break;
        }
        i++;
    }
	// 根据冷端温度的值，找出对应的电压值,并且计算总的电压值
	// 该部分可以参考TI官方的方案
    total_mV = type_k_thermo_lookup_table[i-1].mV + 
          ( type_k_thermo_lookup_table[i].mV     - type_k_thermo_lookup_table[i-1].mV ) *
        ( ( input_cold_junction_C                   - type_k_thermo_lookup_table[i-1].temp_C ) / 
          ( type_k_thermo_lookup_table[i].temp_C - type_k_thermo_lookup_table[i-1].temp_C )  );
    total_mV += input_voltage_mV;
    // 查看电压是否超出范围
    if ( (total_mV < type_k_thermo_lookup_table[0].mV) ||
         (total_mV > type_k_thermo_lookup_table[type_k_thermo_lookup_size-1].mV) ) {
        *output_hot_junction_C = 0;
        return -1;
    }
    // 反向查表
    i=1;
    while ( i<(type_k_thermo_lookup_size-1) ) {
        if ( total_mV <= type_k_thermo_lookup_table[i].mV ) {
            break;
        }
        i++;
    }
	// 将电压转换成温度
    *output_hot_junction_C = type_k_thermo_lookup_table[i-1].temp_C + 
          ( type_k_thermo_lookup_table[i].temp_C - type_k_thermo_lookup_table[i-1].temp_C ) *
        ( ( total_mV                      - type_k_thermo_lookup_table[i-1].mV ) / 
          ( type_k_thermo_lookup_table[i].mV     - type_k_thermo_lookup_table[i-1].mV )  );
    return 0;
}

uint16_t ads1118_get_differential_0_1(uint8_t PGA) {
	uint16_t adc=0;
	ADS_InitTypeDef ConfigReg;
	ConfigReg.stru.NOP		=	DATA_VALID;
	ConfigReg.stru.TS_MODE	=	ADC_MODE;
	ConfigReg.stru.DR       =  	DR_860_SPS;
	ConfigReg.stru.PGA      = 	PGA;
	ConfigReg.stru.MODE		=	SIGNLE_SHOT;
	ConfigReg.stru.OS		=	SINGLE_CONVER_START;   //high
	ConfigReg.stru.MUX		=	AINPN_0_1;
	ConfigReg.stru.PULLUP	= 	PULL_UP_EN;
	ConfigReg.stru.RESV		= 	CONFIG_BIT_RESV;
	ADS1118_ENABLE;
	// delay_us((uint32_t)1);
	adc = SPI_ReadWrite16Bit(ConfigReg.word);
	ADS1118_DISABLE;
	HAL_Delay(1);
	ADS1118_ENABLE;
	ConfigReg.stru.NOP		=	DATA_INVALID;
	ConfigReg.stru.TS_MODE	=	ADC_MODE;
	ConfigReg.stru.DR       =  	DR_860_SPS;
	ConfigReg.stru.PGA      = 	PGA;
	ConfigReg.stru.MODE		=	SIGNLE_SHOT;
	ConfigReg.stru.OS		=	SINGLE_CONVER_START;   //high
	ConfigReg.stru.MUX		=	AINPN_0_1;
	ConfigReg.stru.PULLUP	= 	PULL_UP_EN;
	ConfigReg.stru.RESV		= 	CONFIG_BIT_RESV;
	// delay_us((uint32_t)1);
	//等待DOUT给出数据有效信号-从高变低
	// while(GPIO_ReadInputDataBit(SPI_MASTER_GPIO,SPI_MASTER_PIN_MISO));
	HAL_Delay(3);
	adc = SPI_ReadWrite16Bit(ConfigReg.word);
	// delay_us(1);
	ADS1118_DISABLE;
	return   adc;
}
// 中值滤波
uint16_t ads1118_median_filter(uint16_t *pbuffer) {  
	uint16_t value_buf_input[SAMPLECOUNTER];  
	uint8_t i,j,temp;
	memcpy(value_buf_input,pbuffer,SAMPLECOUNTER * sizeof(uint16_t));
	for (j = 0; j < SAMPLECOUNTER - 1; j++) {
        for (i = 0; i < SAMPLECOUNTER - j - 1; i++) {
            if (value_buf_input[i] > value_buf_input[i + 1]) {
                temp = value_buf_input[i];
                value_buf_input[i] = value_buf_input[i + 1];
                value_buf_input[i + 1] = temp;
            }
        }
    }
	return value_buf_input[(SAMPLECOUNTER-1)/2];
}

// 中位值平均滤波
double ads1118_median_average_filter(double *pbuffer) {
    uint8_t count, i, j;
    double value_buf_input[SAMPLECOUNTER];
    double sum = 0, temp;
    memcpy(value_buf_input, pbuffer, SAMPLECOUNTER * sizeof(double));
    // 冒泡排序
    for (j = 0; j < SAMPLECOUNTER - 1; j++) {
        for (i = 0; i < SAMPLECOUNTER - j - 1; i++) {
            if (value_buf_input[i] > value_buf_input[i + 1]) {
                temp = value_buf_input[i];
                value_buf_input[i] = value_buf_input[i + 1];
                value_buf_input[i + 1] = temp;
            }
        }
    }
    // 去掉最小值与最大值后求平均值
    for (count = 1; count < SAMPLECOUNTER - 1; count++)
        sum += value_buf_input[count];
    return sum / (SAMPLECOUNTER - 2);
}


double ads1118_get_differential_0_1_mv(uint8_t PGA) {
	double t_mv=0.0;
	uint8_t i;
	uint16_t adc_raw[SAMPLECOUNTER],adc_raw_final;
	for(i=0;i<SAMPLECOUNTER;i++)
		adc_raw[i] = ads1118_get_differential_0_1(PGA);
	adc_raw_final = ads1118_median_filter(adc_raw);
	switch(PGA) {
		case PGA_6144:
			t_mv =  adc_raw_final * ADS1118_CONST_6_144V_LSB_mV;
			break;
		case PGA_4096:
			t_mv =  adc_raw_final * ADS1118_CONST_4_096V_LSB_mV;
			break;
		case PGA_2048:
			t_mv =  adc_raw_final * ADS1118_CONST_2_048V_LSB_mV;
			break;
		case PGA_1024:
			t_mv =  adc_raw_final * ADS1118_CONST_1_024V_LSB_mV;
			break;
		case PGA_512:
			t_mv =  adc_raw_final * ADS1118_CONST_0_512V_LSB_mV;
			break;
		case PGA_256:
			t_mv =  adc_raw_final * ADS1118_CONST_0_256V_LSB_mV;
			break;
		default:
			break;
	}
	return t_mv;
}
